package com.hm.base.service;

import java.io.File;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hm.base.auto.SystemEnvConfigProperties;
import com.hm.base.vo.LocalDatabaseStoreVo;
import com.hm.common.util.DateUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @author shishun.wang
 * @date 下午3:25:38 2017年8月25日
 * @version 1.0
 * @describe
 */
@Slf4j
@Service
public class LocalDatabaseStoreServiceImpl implements LocalDatabaseStoreService {

	@Autowired
	private SystemEnvConfigProperties systemEnvConfigProperties;

	@Override
	public List<LocalDatabaseStoreVo> query() {
		List<LocalDatabaseStoreVo> vos = new ArrayList<LocalDatabaseStoreVo>();
		String path = systemEnvConfigProperties.getDatabaseBackUp().getBackUpFilePath().endsWith("/")
				? systemEnvConfigProperties.getDatabaseBackUp().getBackUpFilePath().substring(0,
						systemEnvConfigProperties.getDatabaseBackUp().getBackUpFilePath().length() - 1)
				: systemEnvConfigProperties.getDatabaseBackUp().getBackUpFilePath();
		File storeFolder = new File(path);
		if (!storeFolder.exists()) {
			log.warn("{}，数据库本地存储目录不存在", path);
			return vos;
		}

		long index = 1;
		for (File file : storeFolder.listFiles()) {
			if (file.getName().endsWith(".zip")) {
				continue;
			}
			LocalDatabaseStoreVo vo = new LocalDatabaseStoreVo();
			vo.setId(index);
			vo.setFileName(file.getName());
			vo.setFilePath(file.getPath());
			vo.setFileSize(trace(file.length() / 1000));
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			try {
				vo.setCreateTime(DateUtil.data2long(format.parse(file.getName().replaceAll(".sql", ""))));
			} catch (ParseException e) {
				log.error(e.getMessage(), e);
			}

			vos.add(vo);
			index++;
		}

		return vos;
	}

	private static double trace(double data) {
		BigDecimal b = new BigDecimal(data);
		return b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
	}

	public static void main(String[] args) throws Exception {
		List<LocalDatabaseStoreVo> vos = new ArrayList<LocalDatabaseStoreVo>();
		String path = "D:/tmp/mysql";
		File storeFolder = new File(path);
		if (!storeFolder.exists()) {
			log.warn("{}，数据库本地存储目录不存在", path);
			return;
		}
		for (File file : storeFolder.listFiles()) {
			LocalDatabaseStoreVo vo = new LocalDatabaseStoreVo();
			vo.setFileName(file.getName());
			vo.setFilePath(file.getPath());
			vo.setFileSize(trace(file.length() / 1000));
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			vo.setCreateTime(DateUtil.data2long(format.parse(file.getName().replaceAll(".sql", ""))));

			vos.add(vo);
		}

		System.out.println(vos);
	}

}
